﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using Scrabble.Model.Events;

namespace Scrabble.Model
{
    public partial class Game
    {
        class HistoricTimeKeeper : ITimeKeeper
        {
            public TimeSpan TimeInPlay { get; set; }
        }

        #region Serialization

        public StateOfPlay StateOfPlay
        {
            get
            {
                return new StateOfPlay
                {
                    Seed = _sequence.Seed,
                    NamesOfPlayers = _setOfPlayers.Select(player => player.Name).ToArray(),
                    // SetOfPlays = _history.Select(play => play.ToNotation()).ToArray(),
                    EventLog = _eventLog.Select(play => play.ToRecordOfPlay()).ToArray(),
                };
            }
        }

        public static Game FromStateOfPlay(StateOfPlay stateOfPlay)
        {
            var timeKeeper = new HistoricTimeKeeper();
            var game = new Game(stateOfPlay.Seed, stateOfPlay.NamesOfPlayers) { TimeKeeper = timeKeeper };

            if (stateOfPlay.EventLog != null)
            {
                foreach (var play in stateOfPlay.EventLog)
                {
                    timeKeeper.TimeInPlay = play.DurationOfPlay;
                    game.PlayFromNotation(play.Type, play.Notation);
                }
            }
            //else
            //{
            //    foreach (var play in stateOfPlay.SetOfPlays)
            //        game.PlayFromNotation(TimeSpan.Zero, play);
            //}

            game.TimeKeeper = new BasicTimeKeeper(game);
            return game;
        }

        #endregion

        private void PlayFromNotation(string notation)
        {
            var groups = Regex.Match(notation, @"(?<action>[a-z]+:)(?<notation>.+)?").Groups;
            PlayFromNotation(groups["action"].Value, groups["notation"].Success ? groups["notation"].Value : String.Empty);
        }

        private void PlayFromNotation(string actionType, string notation)
        {
            var player = (Player)ActivePlayer;
            if (player == null) return;

            switch (actionType)
            {
                case ActionType.Pass:
                    player.Pass();
                    break;

                case ActionType.Exchange:
                    player.ExchangeTiles(player.TilesFromLetters(notation).ToArray());
                    break;

                case ActionType.Play:
                    player.PlaceTilesFromNotation(notation);
                    break;

                case ActionType.Deduct:
                case ActionType.EndBonus:
                    break;

                default:
                    Guard.Against<FormatException>(true, "invalid format");
                    return;
            }
        }
    }
}
